package com.example.post.controller;

import com.example.post.model.Message;
import com.example.post.model.ResponseData;
import com.example.post.model.User;
import com.example.post.services.MessageService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @PostMapping("/send")
    public ResponseEntity<String> sendMessage(HttpSession session, @RequestBody Message message) {
        String content=message.getContent();
        int  receiverId=message.getReceiverId();
        User user = (User) session.getAttribute("user");
        message.setSenderId(user.getId());
        messageService.sendMessage(user.getId(),receiverId,content);
        return ResponseEntity.status(HttpStatus.OK).body("发送成功");
    }
    @GetMapping("/messages")
    public ResponseData getMessages(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Message> messages = messageService.getMessages(user.getId());
        System.out.println(messages);
        ResponseData res;
        if (messages.isEmpty()){
            res = new ResponseData(500,"查询出错","");
        }else{
            res = new ResponseData(200,"查询成功",messages);
        }
        return res;
    }
    @GetMapping("/MyMessAges")
    public ResponseData getMessagesmy(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Message> messages = messageService.getMyMessages(user.getId());
        System.out.println(messages);
        ResponseData res;
        if (messages.isEmpty()){
            res = new ResponseData(500,"查询出错","");
        }else{
            res = new ResponseData(200,"查询成功",messages);
        }
        return res;
    }
}


